package org.fog.json.io;

import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.fog.json.common.JsonMapReaderType;
import org.fog.json.map.JsonMapBody;
import org.fog.json.map.JsonMapPackage;

import java.io.File;
import java.net.URI;
import java.util.TreeMap;

/**
 * User: 缪凯
 * Date: 12-2-8
 * Time: 上午10:04
 */
public class JsonMapReaderImp implements JsonMapReader {
    private File file = null;
    private JsonMapReaderType type = JsonMapReaderType.Damage;
    private JsonMapParser parser = null;

    public JsonMapReaderImp(URI path){
        if(path != null)
            new JsonMapReaderImp(new File(path));
    }

    public JsonMapReaderImp(File file){
        if(file != null)
            this.file = file;
    }

    public JsonMapPackage readPackage() {
        if(this.type == JsonMapReaderType.Ready)
            return this.parser.getPackage();

        return null;
    }

    public TreeMap<String, JsonMapBody> readBodies() {
        if(this.type == JsonMapReaderType.Ready)
            return this.parser.getBodies();
        return null;
    }

    public JsonMapBody readBody(String name) {
        if(this.type == JsonMapReaderType.Ready && name != null && !"".equals(name))
            return this.parser.getBodies().get(name);
        return null;
    }

    public JsonMapReaderType makeReady() {
        //todo 增加dtd校验
        SAXReader reader = new SAXReader();
        try {
            if(this.parser == null)
                this.parser =  new JsonMapParserImp(reader.read(this.file));
            this.type = JsonMapReaderType.Ready;
        } catch (DocumentException e) {
            e.printStackTrace();
            this.type = JsonMapReaderType.Damage;
        }
        return this.type;
    }

    public static void main(String[] args){
        JsonMapReader reader =
                new JsonMapReaderImp
                        (URI.create("file:///D:/Space/project/learn-free/config/fog/json-audit-resource.xml"));
        if(reader.makeReady() == JsonMapReaderType.Ready){
            JsonMapPackage pack =  reader.readPackage();
        }
    }
}
